package com.scau.database.service.aftersalesstaff;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.scau.data.entity.*;
import com.scau.database.common.service.ImportMapperService;
import com.scau.database.entity.aftersale.delay.ApplyDelayVO;
import com.scau.database.entity.aftersale.delay.FinishDelayInIdVO;
import com.scau.database.entity.aftersale.delay.SearchDelayInPhoneVO;
import com.scau.database.entity.aftersale.delay.SearchDelaysResultVO;
import com.scau.database.entity.aftersale.manage.ExchangeGoodsVO;
import com.scau.database.entity.aftersale.manage.GoodsDTO;
import com.scau.database.entity.aftersale.manage.ReturnGoodsVO;
import com.scau.database.enums.AfterSalesTypeEnum;
import com.scau.database.enums.ExchangeGoodsFinishedEnum;
import com.scau.database.enums.ExchangeGoodsTypeEnum;
import com.scau.database.enums.IsFinishedEnum;
import com.scau.database.exception.APIException;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @ClassName: DelayService
 * @Description: TODO 售后的服务层
 * @Author: sunslikes
 * @Date: 2020/6/26 1:30
 * @Version: 1.0
 */
@Service
public class DelayService {

    @Autowired
    AfterSalesService afterSalesService;
    @Autowired
    ImportMapperService importMapperService;

    @Transactional
    public String applyDelay(ApplyDelayVO delayVO) {
        Date date = new Date();
        ExchangeGoodsVO goodsVO = delayVO.getExchangeGoodsVO();
        GoodsDTO goodsDTO = afterSalesService.getGoodsDTO(goodsVO.getShopId(), goodsVO.getBarCode(), AfterSalesTypeEnum.EXCHANGE);
//        ExchangeGoodsVO goodsVO = delayVO.getExchangeGoodsVO();

        if (goodsVO.getCount() > goodsDTO.getShopLineDO().getCount()) {
            throw new APIException("您输入的数量有误！");
        }
        ExchangeGoodsDO exchangeGoodsDO = new ExchangeGoodsDO();
        BeanUtils.copyProperties(goodsVO, exchangeGoodsDO);
        exchangeGoodsDO.setOrderNumber(goodsDTO.getShopLineDO().getOrderNumber());
        exchangeGoodsDO.setShelfId(goodsDTO.getShopLineDO().getShelfId());
        System.out.println(exchangeGoodsDO);
        switch (goodsDTO.getGoodsProtectionTypeEnum()) {
            case FACTORY:
                //厂保
                exchangeGoodsDO.setType(ExchangeGoodsTypeEnum.EXCHANGE_FACTORY.getType());
                exchangeGoodsDO.setFinished(ExchangeGoodsFinishedEnum.NOT_DEAL.getType());
                OrderDO orderDOCondition = new OrderDO();
                orderDOCondition.setOrderNumber(goodsDTO.getShopLineDO().getOrderNumber());
                Integer warehouseId = importMapperService.returnGoodsMapper.getWarehouseId(goodsDTO.getShopLineDO().getShelfId());
                orderDOCondition.setWarehouseId(warehouseId);
                OrderDO orderDO = importMapperService.orderMapper.selectOne(new QueryWrapper<>(orderDOCondition).last("limit 1"));
                if (orderDO == null) {
                    throw new APIException("订单错误！");
                }
                Integer factoryId = orderDO.getFactoryId();
                FactoryExchangeDO factoryExchangeDO = new FactoryExchangeDO();
                factoryExchangeDO.setFactoryId(factoryId);
                factoryExchangeDO.setBarCode(goodsVO.getBarCode());
                factoryExchangeDO.setCount(goodsVO.getCount());
                factoryExchangeDO.setTime(date);
                factoryExchangeDO.setServiceId(goodsVO.getServiceId());
                factoryExchangeDO.setFinished(false);
            // 把货寄给工厂
            // 填写owe表等待工厂发货过来
                OweDO oweDO = new OweDO();
                oweDO.setBarCode(goodsVO.getBarCode());
                oweDO.setCount(goodsVO.getCount());
                oweDO.setCustomer(delayVO.getCustomer());
                oweDO.setPhone(delayVO.getPhone());
                oweDO.setTime(date);
                oweDO.setServiceId(goodsVO.getServiceId());
                oweDO.setFinished(false);
                importMapperService.exchangeGoodsMapper.insert(exchangeGoodsDO);
                importMapperService.factoryExchangeMapper.insert(factoryExchangeDO);
                importMapperService.oweMapper.insert(oweDO);
                FactoryDO factoryDO = importMapperService.factoryMapper.selectById(factoryId);
                return "等待单号：" + oweDO.getId() + "请联系工厂：" + factoryDO.getPhone() + "，并安排发货";
            case STORE:
                //店保
                if (!goodsDTO.getSalesStoreId().equals(goodsVO.getServiceId())) {
                    throw new APIException("已过厂保，店保产品请到原购买店。");
                }
                exchangeGoodsDO.setType(ExchangeGoodsTypeEnum.EXCHANGE_STORE.getType());
                // 查询是否有货
                OnSellDO onSellDOCondition = new OnSellDO();
                onSellDOCondition.setStoreId(goodsVO.getServiceId());
                onSellDOCondition.setBarCode(goodsVO.getBarCode());
                OnSellDO onSellDO = importMapperService.onsellMapper.selectOne(new QueryWrapper<>(onSellDOCondition).last("limit 1"));
                if (onSellDO == null) {
                    throw new APIException("错误请求");
                } else if (onSellDO.getSurplus() < goodsVO.getCount()) {
                    return "shop_owe";
                }
                // 写欠条
                OweDO storeOweDO = new OweDO();
                storeOweDO.setBarCode(goodsVO.getBarCode());
                storeOweDO.setCount(goodsVO.getCount());
                storeOweDO.setCustomer(delayVO.getCustomer());
                storeOweDO.setPhone(delayVO.getPhone());
                storeOweDO.setTime(date);
                storeOweDO.setServiceId(goodsVO.getServiceId());
                storeOweDO.setFinished(false);
                if (goodsVO.getCanResell()) {
                    afterSalesService.resellGoods(goodsDTO, goodsVO.getCount());
                }
                importMapperService.exchangeGoodsMapper.insert(exchangeGoodsDO);
                importMapperService.oweMapper.insert(storeOweDO);
                return "等待单号" + storeOweDO.getId();
        }
        throw new APIException("无保修");
    }


    public String finishDelay(FinishDelayInIdVO vo) {
        OweDO oweDO = importMapperService.oweMapper.selectById(vo.getId());
        if (oweDO == null) {
            throw new APIException("没有这笔欠单");
        }
        if (!oweDO.getServiceId().equals(vo.getServiceId())) {
            throw new APIException("服务商错误，您不能完成这笔订单。");
        }
        oweDO.setFinished(true);
        importMapperService.oweMapper.updateById(oweDO);
        return "ok";
    }

    /**
     * 通过服务商id和电话号码查询
     * @param vo
     * @return
     */
    public List<SearchDelaysResultVO> listDelaysAboutPhoneAndSeriveid(SearchDelayInPhoneVO vo) {
        LambdaQueryWrapper<OweDO> oweDOLambdaQueryWrapper = Wrappers.<OweDO>lambdaQuery()
                .eq(OweDO::getPhone, vo.getPhone())
                .eq(OweDO::getServiceId, vo.getServiceId())
                .eq(OweDO::getFinished, false)
                .orderByDesc(OweDO::getTime);
        List<OweDO> oweDOS = importMapperService.oweMapper.selectList(oweDOLambdaQueryWrapper);
        List<SearchDelaysResultVO> resultVOS = new ArrayList<>();
        for (OweDO oweDO : oweDOS) {
            SearchDelaysResultVO resultVO = new SearchDelaysResultVO();
            BeanUtils.copyProperties(oweDO, resultVO);
            resultVOS.add(resultVO);
        }
        return resultVOS;
    }

}
